#include <qqtvirtualdatamanager.h>
#include <qqthostaddressmanager.h>

QQtVirtualDataManager::QQtVirtualDataManager ( QObject* parent )
    : QObject ( parent )
{
    c0 = 0;
    p0 = 0;
}

QQtVirtualDataManager::~QQtVirtualDataManager() {}

void QQtVirtualDataManager::setClientHandler ( QQtUdpClient* handler )
{
    c0 = handler;
}

QQtUdpClient* QQtVirtualDataManager::handler()
{
    return c0;
}

void QQtVirtualDataManager::setProtocolHandler ( QQtDataProtocol* protocol )
{
    p0 = protocol;
    c0->installProtocol ( p0 );
    connect ( p0, SIGNAL ( readyRead ( const QQtDataSerialization& ) ),
              this, SIGNAL ( readyRead ( const QQtDataSerialization& ) ) );
}

QQtDataProtocol* QQtVirtualDataManager::protocol()
{
    return p0;
}

void QQtVirtualDataManager::sendMessage ( const QQtDataSerialization& data )
{
    p0->sendMessage ( data );
}

void QQtVirtualDataManager::setServerAddress ( QHostAddress address, int port )
{
    c0->setServerAddress ( address, port );
    p3line() << address.toString() << port;
}

void QQtVirtualDataManager::setServerPort ( int port )
{
    c0->setServerAddress ( QHostAddress ( QHostAddress::Broadcast ), port );
    p3line() << QHostAddress ( QHostAddress::Broadcast ) << port;
}

void QQtVirtualDataManager::setListeningAddress ( QHostAddress address, int port )
{
    c0->disconnectFromHost();
    c0->bind ( address, port, QQtUdpClient::DefaultForPlatform );
    p3line() << c0->localAddress() << c0->localPort();
}

void QQtVirtualDataManager::setListeningPort ( int port )
{
    c0->disconnectFromHost();
    QQtHostAddressManager manager;
    QString ip = manager.getHostAddress();
#if USE_HOST_ADDRESS
    c0->bind ( QHostAddress ( ip ), port, QQtUdpClient::DefaultForPlatform );
#else
    c0->bind ( port, QQtUdpClient::DefaultForPlatform );
#endif
    p3line() << c0->localAddress() << c0->localPort();
}
